var express = require('express')
var md5 = require('md5')
var axios = require('axios')

var User = require('../models/wxuser')
var Theme = require('../models/theme')
var Comment = require('../models/comment')
var upload = require("../models/upload")
var config = require("../config/config")
var { decryptByAES , encryptSha1 } = require('../util/util')
var { saveUserInfo } = require('../controllers/users')

var router = express.Router()

//get 请求
router.get('/', function (req, res, next) { 

    //查询mongodb数据库中themes集合内所有的主题列表      
    Theme.find(function (err, theme) {
        if (err) {
            console.log(err.message)
            return next(err)
        }
        var newtheme = JSON.parse(JSON.stringify(theme))

        //希望通过for循环遍历theme主题列表
        var indexArr=[]
        newtheme.forEach(function(item,index){
            //根据theme主题中的作者ID查询users集合内对应的用户详情
            User.findOne({_id:item.authorId},function(err,user){

                indexArr.unshift(index)
                //给每个主题新增一个字段authorName，将查询到的用户名称赋值给这个字段
                item.authorName = user.nickname
                item.authorAva = user.avatar

                if(indexArr.length===newtheme.length){
                    
                    res.status(200).json({
                        code: 0,
                        msg: '加载成功',
                        user: req.session.user,
                        theme: newtheme
                    })

                    // res.status(200).render('./list.art', {
                    //     code:0,
                    //     msg:'加载成功',
                    //     user: req.session.user,
                    //     theme: theme
                    // })

                }
            })            
        })




    }).sort({ _id: -1 })

})
router.get('/login', function (req, res, next) {
    res.render('login.art')
})
router.post('/login', function (req, res, next) {

    User.findOne({
        email: req.body.inputEmail,
        password: md5(md5(req.body.inputPassword))
    }, function (err, user) {
        if (err) {
            return next(err)
        }

        if (!user) {
            return res.status(200).json({
                code: 1,
                msg: '邮箱或者密码错误！请检查后再试。'
            })
        }

        req.session.user = user
        res.status(200).json({
            code: 0,
            msg: '登录成功！',
            user: user
        })
    })
})

// 微信登录
router.post('/wxlogin',function(req,res,next){
    const {
        code,
        encryptedData,
        iv,
    } = req.body
    const {appid,secret,grant_type} = config
    const opt = {
        method:'get',
        url:'https://api.weixin.qq.com/sns/jscode2session',
        params:{
            appid:appid,
            secret:secret,
            js_code:code,
            grant_type:grant_type
        }
      }

    axios(opt)
    .then(function(resdata){
        const data = resdata.data
        const {session_key} = data
        const skey = encryptSha1(session_key)
        let decryptedData = JSON.parse(decryptByAES(encryptedData,session_key,iv))
        return saveUserInfo({
            userInfo:decryptedData,
            session_key,
            skey
        })
    })
    .then(function(logindata){  
        res.status(200).json(logindata)
    })
})

router.get('/logout', function (req, res, next) {
    delete req.session.user
    res.redirect('/login')
})

router.get('/register', function (req, res, next) {
    res.render('register.art')
})
router.post('/register', function (req, res, next) {
    User.findOne({
        email: req.body.inputEmail
    }, function (err, data) {
        if (err) {
            return next(err)
        }
        if (data) {
            return res.status(200).json({
                code: 1,
                msg: '邮箱已被注册！'
            })
        }
        new User({
            email: req.body.inputEmail,
            nickname: req.body.inputName,
            password: md5(md5(req.body.inputPassword)),
        }).save(function (err, user) {
            if (err) {
                return next(err)
            }
            req.session.user = user
            res.status(200).json({
                code: 0,
                msg: '注册成功',
                user: user,
            })
        })
    })
})

router.post('/delectUser',function(req,res,next){
    User.deleteOne({_id:req.body.id},function(err,data){
        if(err){
            console.log(err)
            return next(err)
        }
        res.status(200).json({
            code:0,
            msg:'注销成功'
        })
    })
})

router.post('/updatePsw',function(req,res,next){
    User.findOne({_id:req.body.uid},function(err,user){
        if(err){
            console.log(err)
            return next(err)
        }
        if(md5(md5(req.body.oldPsw)) != user.password){
            return res.status(200).json({
                    code:1,
                    msg:'用户密码不正确'
            })
        }
        User.findOneAndUpdate({_id:req.body.uid},{password:md5(md5(req.body.newPsw))},{ new: true },function(err,date){
            if(err){
                console.log(err)
                return next(err)
            }
            res.status(200).json({
                code:0,
                msg:"密码修改成功",
                user:date
            })
        })
    })

})


router.get('/content', function (req, res, next) {
    console.log(req.query)
})
router.get('/publish', function (req, res) {
    res.render('publish.art', {
        user: req.session.user
    })
})
router.post('/publish', function (req, res, next) {
    new Theme({
        title: req.body.title,
        content: req.body.content,
        authorId: req.body._id
    }).save(function (err, theme) {
        if (err) {
            return next(err)
        }
        res.status(200).json({
            code: 0,
            msg: '发表成功',
            theme: theme
        })
    })
})

router.get('/comment',function(req,res,next){
    Comment.find({topic_id:req.query.id},function(err,comment){
        if(err){
            console.log(err)
            return next(err)
        }
        var newComment = JSON.parse(JSON.stringify(comment))
        var dataArr = []
        newComment.forEach(function(item,index){
            User.findOne({_id:item.from_uid},function(err,user){
                dataArr.push(index)
                item.from_uname = user.nickname
                item.from_uname_avatar = user.avatar
                if(dataArr.length === newComment.length){
                    res.json({
                        code:0,
                        msg:'评论查询成功',
                        comment:newComment
                    })

                }
            })
        })
    })

})

router.post('/comment',function(req,res,next){
    new Comment(req.body).save(function(err,data){
        if(err){
            console.log(res)
            return next(err)
        }
        console.log(data)
        res.status(200).json({
            code:0,
            msg:"评论成功",
            comment:data
        })
    })
})

router.get('/setting', function (req, res, next) {

    res.render('setting.art', {
        user: req.session.user

    })
})
router.post('/setting', function (req, res, next) {

    req.body.last_modified_time = Date.now()
    User.findOneAndUpdate({_id:req.body._id}, req.body, { new: true }, function (err, user) {
        if (err) {
            return next(err)
        }
        req.session.user = user
        res.status(200).json({
            code: 0,
            msg: '修改成功',
            user,
        })
    })


    // req.body.last_modified_time = Date.now()
    // console.log(req.session.user,req.body)
    // User.findByIdAndUpdate(req.session.user._id, req.body, { new: true }, function (err, data) {
    //     if (err) {
    //         return res.status(500).json({
    //             code: 500,
    //             msg: '数据库错'
    //         })
    //     }
    //     req.session.user = data
    //     res.status(200).json({
    //         code: 0,
    //         msg: '修改成功'
    //     })
    // })

})

router.post('/updateAva', function (req, res, next) {
    upload( req,res,next)
})



module.exports = router

